package lib.bone.nepudata.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Validator;
import lib.bone.access.constant.ResearchTypeConst;
import lib.bone.common.constant.ResponseCodeConst;
import lib.bone.common.core.domain.PageResultDTO;
import lib.bone.common.core.domain.ResponseDTO;
import lib.bone.common.exception.BusinessException;
import lib.bone.common.utils.JsonUtil;
import lib.bone.flow.domain.dto.FlowParam;
import lib.bone.flow.domain.dto.PaperFlowWorkDTO;
import lib.bone.flow.domain.dto.PaperFlowWorkItem;
import lib.bone.flow.domain.entity.FlowWork;
import lib.bone.flow.service.FlowWorkService;
import lib.bone.nepudata.dao.NepuPaperDAO;
import lib.bone.nepudata.domain.entity.NepuPaper;
import lib.bone.nepudata.expose.WorkloadService;
import lib.bone.nepudata.service.NepuPaperService;
import lib.bone.nepudata.service.ResearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class NepuPaperServiceImpl implements ResearchService<NepuPaper,String>, NepuPaperService {


    @Autowired
    private NepuPaperDAO nepuPaperDAO;

    @Autowired(required = false)
    WorkloadService workloadService;

    @Autowired
    FlowWorkService flowWorkService;

    @Override
    public List<NepuPaper> getByIds(List<String> ids) {
        return nepuPaperDAO.findByIdIn(ids);
    }

    @Override
    public List<NepuPaper> findByExample(Example<NepuPaper> example) {
        return nepuPaperDAO.findAll(example);
    }

    //    @Autowired
//    NepuResearchWorkloadDAO nepuResearchWorkloadDAO;


    @Override
    public String getProjectCode(String s) {
        Optional<NepuPaper> paperOp = getById(s);
        if (paperOp.isPresent()){
            return paperOp.get().getIssueNumber();
        }else {
            return "无";
        }
    }

    @Override
    public String getServiceType() {
        return ResearchTypeConst.PAPER;
    }

    @Override
    public PageResultDTO<NepuPaper> getAll(Pageable pageable, Example<NepuPaper> example) {
        Page<NepuPaper> nepuPaperPage;
        //是否为空 --
        if(Validator.isEmpty(example)){
            nepuPaperPage = nepuPaperDAO.findAll(pageable);
        }else {
            nepuPaperPage = nepuPaperDAO.findAll(example,pageable);
        }
        List<NepuPaper> nepuPaperList = nepuPaperPage.getContent();
        PageResultDTO<NepuPaper> pageResultDTO = new PageResultDTO<>();
        pageResultDTO.setContent(nepuPaperList);
        pageResultDTO.setSize(nepuPaperPage.getSize());
        pageResultDTO.setTotalPages(nepuPaperPage.getTotalPages());
        pageResultDTO.setNumber(nepuPaperPage.getNumber());
        pageResultDTO.setTotalElements(nepuPaperPage.getTotalElements());

        return pageResultDTO;
    }

    @Override
    public ResponseDTO deleteById(String id) {
        //
        Integer useCount = workloadService.countByLinkId(id);
        // Long useCount = nepuResearchWorkloadDAO.countByResearchTypeAndMapperId("教学科研获奖",id);
        if(useCount > 0){
            return ResponseDTO.wrap(ResponseCodeConst.FORBIDDEN,"存在关联该奖励的科研工作量信息,拒绝执行删除!");
        }
        //判断数据是否存在
        Optional<NepuPaper> nepuAwardOp = nepuPaperDAO.findById(id);
        if(!nepuAwardOp.isPresent()) return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"ID:["+id+"]对应数据不存在");
        nepuPaperDAO.deleteById(id);
        return ResponseDTO.succMsg("删除成功!");
    }
    @Override
    public Optional<NepuPaper> getById(String id) {
        return nepuPaperDAO.findById(id);
    }

//    @Override
//    public ResponseDTO apply(String id) {
//        NepuPaper nepuPaper = getById(id).get();
//        //更新状态为     1：申请
//        nepuPaper.setApplyStatus(ApplyStatus.APPLY_SUBMIT);
//        return ResponseDTO.succData(nepuPaperDAO.save(nepuPaper));
//    }

    @Override
    public NepuPaper saveOne(NepuPaper nepuPaper){
        if (Validator.isNotEmpty(nepuPaper.getId())){
            throw new BusinessException(ResponseCodeConst.ERROR_PARAM);
        }
        return nepuPaperDAO.save(nepuPaper);
    }

    @Override
    public NepuPaper updateOne(NepuPaper nepuPaper) {
        //@TODO 如果在审核流程中 应拒绝修改，或者修改后退回初始流程位置
        if (Validator.isEmpty(nepuPaper.getId())){
            throw new BusinessException(ResponseCodeConst.ERROR_PARAM);
        }
        return nepuPaperDAO.save(nepuPaper);
    }
    /**
     * 根据论文名称和第一作者询
     * @param
     * @return
     */
    public Optional<NepuPaper> getByPaperTitleAndFirstAuthor(String paperTitle,String firstAuthor){
        return nepuPaperDAO.findByPaperTitleAndFirstAuthor(paperTitle,firstAuthor);
    }


    public ResponseDTO status(Long userId) {
        List<NepuPaper> nepuPapers = nepuPaperDAO.findAllByFirstAuthorId(userId);
        for (NepuPaper nepuPaper : nepuPapers) {
            if (nepuPaper.getStatus()!=null){
                return ResponseDTO.succData(1);
            }
        }
        return ResponseDTO.succData(0);

    }

    public ResponseDTO updateList(PaperFlowWorkDTO dto) {
        String loginId = StpUtil.getLoginIdAsString();
        if (loginId==null){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"未提供token！");
        }
        List<PaperFlowWorkItem> flowWorkList = dto.getItems();
        if (flowWorkList.size()==0){
            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"您没有进行中或者已结束的论文！");
        }
        for (PaperFlowWorkItem paperFlowWork : flowWorkList) {
            Optional<FlowWork> flowWorkOp = flowWorkService.getById(paperFlowWork.getId());
            if (!flowWorkOp.isPresent()){
                return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,paperFlowWork.getId()+"数据不存在！");
            }
            FlowWork flowWork = new FlowWork();
            BeanUtil.copyProperties(flowWorkOp.get(),flowWork, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
            System.out.println("flow"+flowWork);
            System.out.println("论文流程"+flowWorkOp.get());
            FlowParam param = JsonUtil.string2Obj(flowWork.getFlowParam(),FlowParam.class);
            Optional<NepuPaper> paperOp = this.getById(param.getServiceId());
            if (!paperOp.isPresent()){
                return ResponseDTO.succData(flowWork.getId()+"对应的论文不存在！");
            }
            NepuPaper paper = new NepuPaper();
            BeanUtil.copyProperties(paperOp.get(),paper, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
            paper.setStatus(paperFlowWork.getPaperStatus());
            this.updateOne(paper);

        }

        return ResponseDTO.succData("流程实例更新成功!");

    }

//
//    @Override
//    public ResponseDTO deleteById(String id) {
//        Optional<NepuPaper> optional = nepuPaperDAO.findById(id);
//        if(!optional.isPresent())
//            return ResponseDTO.wrap(ResponseCodeConst.NOT_FOUND,"ID:["+id+"]对应数据不存在");
//        nepuPaperDAO.deleteById(id);
//        return ResponseDTO.succMsg("删除成功");
//    }
//
//    public ResponseDTO save(NepuPaper nepuPaper) {
//        return ResponseDTO.succData(nepuPaperDAO.save(nepuPaper));
//    }
//
//    @Override
//    public ResponseDTO apply(String id) {
//        Optional<NepuPaper> nepuPaper = nepuPaperDAO.findById(id);
//        //已提交
//        nepuPaper.get().setApplyStatus(ApplyStatus.APPLY_SUBMIT);
//        //更新状态
//        nepuPaperDAO.save(nepuPaper.get());
//        NepuPaperAudit nepuPaperAudit = new NepuPaperAudit();
//        nepuPaperAudit.setApplicant(nepuPaper.get().getApplicant());
//        nepuPaperAudit.setPaperId(nepuPaper.get().getId());
//        nepuPaperAudit.setAuditStatus(AuditStatus.AUDIT_NONE);
//        nepuPaperAuditDAO.save(nepuPaperAudit);
//        return ResponseDTO.succMsg("申请成功");
//    }
}
